<template>
  <view class="register-container">
    <!-- 背景图 -->
    <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/6a164d38f01d49e6af11f0d5e4eba5fb.svg" mode="aspectFill" class="register-bg" />

    <!-- Logo和标题区域 -->
    <view class="header">
      <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png" class="logo" />
      <text class="title">注册账号</text>
      <text class="subtitle">创建您的博阳荟账号</text>
    </view>

    <!-- 注册表单区域 -->
    <view class="register-card">
      <view class="form-wrap">
        <wd-form ref="registerFormRef" :model="registerFormData">
          <!-- 用户名输入框 -->
          <view class="form-item">
            <text class="iconfont icon-ziyuanxhdpi input-icon" size="22" color="#165DFF"></text>
            <input
              v-model="registerFormData.username"
              class="form-input"
              placeholder="请输入用户名"
            />
            <wd-icon
              v-if="registerFormData.username"
              name="close-fill"
              size="18"
              color="#9ca3af"
              class="clear-icon"
              @click="registerFormData.username = ''"
            />
          </view>
          <view class="divider"></view>

          <!-- 手机号输入框 -->
          <view class="form-item">
            <text class="iconfont icon-shoujihao input-icon" size="22" color="#165DFF"></text>
            <input
              v-model="registerFormData.mobile"
              class="form-input"
              type="number"
              placeholder="请输入手机号"
              maxlength="11"
            />
            <wd-icon
              v-if="registerFormData.mobile"
              name="close-fill"
              size="18"
              color="#9ca3af"
              class="clear-icon"
              @click="registerFormData.mobile = ''"
            />
          </view>
          <view class="divider"></view>
          
          <!-- 验证码输入框 -->
          <!-- <view class="form-item">
            <text class="iconfont icon-shoujihao input-icon" size="22" color="#165DFF"></text>
            <input
              v-model="registerFormData.verificationCode"
              class="form-input"
              type="number"
              placeholder="请输入验证码"
              maxlength="6"
            />
            <button 
              class="verification-btn"
              :disabled="countdown > 0 || !validateMobile(registerFormData.mobile)"
              @click="handleGetVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
            </button>
          </view> -->
          <!-- <view class="divider"></view> -->
          <view class="form-item address-item">
            <text
              class="address-icon iconfont icon-hangzhengquyuguanli"
              size="22"
              color="#165DFF"
            ></text>
            <wdColPicker @confirm="handleConfirm"></wdColPicker>
          </view>
          <view class="divider"></view>
          <!-- 验证码输入框 -->
          <!-- 密码输入框 -->
          <view class="form-item">
            <text class="iconfont icon-mima input-icon" size="22" color="#165DFF"></text>

            <input
              v-model="registerFormData.password"
              class="form-input"
              type="password"
              placeholder="请输入密码"
              placeholder-style="color: #9ca3af; font-weight: normal;"
            />
            <wd-icon name="eye-close" size="18" color="#9ca3af" class="eye-icon" />
          </view>
          <view class="divider"></view>

          <!-- 确认密码输入框 -->
          <view class="form-item">
            <text class="iconfont icon-querenmima input-icon" size="22" color="#165DFF"></text>

            <input
              v-model="registerFormData.confirmPassword"
              class="form-input"
              type="password"
              placeholder="请确认密码"
              placeholder-style="color: #9ca3af; font-weight: normal;"
            />
            <wd-icon name="eye-close" size="18" color="#9ca3af" class="eye-icon" />
          </view>
          <view class="divider"></view>

          <!-- 注册按钮 -->
          <button
            class="register-btn"
            :disabled="loading"
            :style="loading ? 'opacity: 0.7;' : ''"
            @click="handleRegister"
          >
            注册
          </button>
        </wd-form>

        <!-- 返回登录 -->
        <view class="back-login">
          <text class="back-text">已有账号？</text>
          <text class="back-btn-text" @click="handleBackLogin">返回登录</text>
        </view>

        <!-- 底部协议 -->
        <view class="agreement">
          <text class="text">注册即同意</text>
          <text class="link" @click="navigateToUserAgreement">《用户协议》</text>
          <text class="text">和</text>
          <text class="link" @click="navigateToPrivacy">《隐私政策》</text>
        </view>
      </view>
    </view>

    <wd-toast />
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app";
import { useToast } from "wot-design-uni";
import { ref } from "vue";
import AuthAPI from "@/api/auth"; // 导入注册API
import UserAPI from "@/api/system/user"; // 导入用户API

const registerFormRef = ref();
const toast = useToast();
const loading = ref(false);
import wdColPicker from "@/components/wd-picker/index.vue";

// 注册表单数据
const registerFormData = ref({
  username: "",
  mobile: "",
  areaCode: "",
  // verificationCode: "",
  password: "",
  confirmPassword: "",
  recommenderId: "",
});

// 验证码倒计时状态
const countdown = ref(0);
const timer = ref<NodeJS.Timeout | null>(null);

// 获取重定向参数
const redirect = ref("");
onLoad((options: any) => {
  registerFormData.value.recommenderId = options.userId || "";
  console.log(registerFormData.value.recommenderId);
  if (options) {
    redirect.value = options.redirect ? decodeURIComponent(options.redirect) : "/pages/index/index";
  } else {
    redirect.value = "/pages/index/index";
  }
});

const handleConfirm = (e: any) => {
  if (Array.isArray(e.value) && e.value.length > 0) {
    registerFormData.value.areaCode = e.value[e.value.length - 1];
  }
};

// 获取验证码
const handleGetVerificationCode = () => {
  if (!validateMobile(registerFormData.value.mobile)) {
    toast.error("请输入正确的手机号");
    return;
  }

  // 设置倒计时
  countdown.value = 60;
  
  // 调用获取验证码接口
  UserAPI.getPhoneCode({
    mobile: registerFormData.value.mobile
  }).then(() => {
    toast.success("验证码已发送");
    
    // 开始倒计时
    if (timer.value) {
      clearInterval(timer.value);
    }
    
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        if (timer.value) {
          clearInterval(timer.value);
          timer.value = null;
        }
      }
    }, 1000);
  }).catch((error: any) => {
    toast.error(error.message || "发送验证码失败");
    countdown.value = 0;
  });
};
// 手机号验证函数
const validateMobile = (mobile: string): boolean => {
  // 中国大陆手机号正则表达式：1开头，第二位3-9，后面9位数字
  const mobileRegex = /^1[3-9]\d{9}$/;
  return mobileRegex.test(mobile);
};

// 注册处理
const handleRegister = () => {
  if (loading.value) return;

  // 表单验证
  if (!registerFormData.value.username) {
    toast.error("请输入用户名");
    return;
  }
  if (!registerFormData.value.mobile) {
    toast.error("请输入手机号");
    return;
  }
  if (!validateMobile(registerFormData.value.mobile)) {
    toast.error("请输入正确的手机号格式");
    return;
  }
  // if (!registerFormData.value.verificationCode) {
  //   toast.error("请输入验证码");
  //   return;
  // }
  // if (registerFormData.value.verificationCode.length !== 6) {
  //   toast.error("验证码格式不正确");
  //   return;
  // }
  if (!registerFormData.value.password) {
    toast.error("请输入密码");
    return;
  }
  if (registerFormData.value.password.length < 6) {
    toast.error("密码长度至少6位");
    return;
  }
  if (registerFormData.value.password !== registerFormData.value.confirmPassword) {
    toast.error("两次密码输入不一致");
    return;
  }

  loading.value = true;

  try {
    // 调用注册接口
    AuthAPI.register({
      username: registerFormData.value.username,
      areaCode: registerFormData.value.areaCode,
      password: registerFormData.value.password,
      confirmPassword: registerFormData.value.confirmPassword,
      mobile: registerFormData.value.mobile,
    }).then(() => {
      toast.success("注册成功");
      // 注册成功后跳转到登录页面
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/login/wechat-authorize?registerSuccess=true",
        });
      }, 1000);
    });
  } catch (e: any) {
    toast.error(e.message || "注册失败");
  } finally {
    loading.value = false;
  }
};

// 返回登录
const handleBackLogin = () => {
  uni.navigateTo({
    url: "/pages/login/index",
  });
};

// 跳转到用户协议页面
const navigateToUserAgreement = () => {
  uni.navigateTo({
    url: "/pages/login/protectPrivacy/userAgreement",
  });
};

// 跳转到隐私政策页面
const navigateToPrivacy = () => {
  uni.navigateTo({
    url: "/pages/login/protectPrivacy/privacy",
  });
};

// 组件卸载时清理定时器
import { onUnmounted } from 'vue';
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style lang="scss" scoped>
.address-item {
  display: flex;

  .address-icon {
    margin-right: 0.7rem;
  }
}

.register-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  overflow: hidden;
}

.register-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.header {
  z-index: 2;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 120rpx;
}

.logo {
  width: 140rpx;
  height: 140rpx;
  margin-bottom: 20rpx;
}

.title {
  margin-bottom: 10rpx;
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.subtitle {
  font-size: 28rpx;
  color: #ffffff;
  text-align: center;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.register-card {
  z-index: 2;
  display: flex;
  flex-direction: column;
  width: 90%;
  margin-top: 80rpx;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1);
}

.form-wrap {
  padding: 40rpx;
}

.form-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 24rpx 0;
}

.input-icon {
  margin-right: 20rpx;
  font-size: 40rpx;
}

.form-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  line-height: 60rpx;
  color: #333;
}

.clear-icon,
.eye-icon {
  padding: 10rpx;
}

.verification-btn {
  min-width: 180rpx;
  height: 60rpx;
  padding: 0 16rpx;
  font-size: 24rpx;
  line-height: 60rpx;
  color: #165DFF;
  background-color: transparent;
  border: 1px solid #165DFF;
  border-radius: 30rpx;
  margin-right: 10rpx;
}

.verification-btn:disabled {
  color: #9ca3af;
  border-color: #9ca3af;
}

.divider {
  height: 1px;
  margin: 0;
  background-color: rgba(0, 0, 0, 0.06);
}

.mobile-tip {
  margin-top: 8rpx;
  font-size: 24rpx;
  padding-left: 60rpx; /* 对齐输入框 */
}

.tip-text {
  transition: color 0.3s ease;
}

.tip-text.valid {
  color: #52c41a;
}

.tip-text.invalid {
  color: #ff4d4f;
}

.register-btn {
  width: 100%;
  height: 90rpx;
  margin-top: 60rpx;
  font-size: 32rpx;
  line-height: 90rpx;
  color: #fff;
  background: linear-gradient(90deg, #165dff, #4080ff);
  border: none;
  border-radius: 45rpx;
  box-shadow: 0 8rpx 20rpx rgba(22, 93, 255, 0.3);
  transition: all 0.3s;
}

.register-btn:active {
  box-shadow: 0 4rpx 10rpx rgba(22, 93, 255, 0.2);
  transform: translateY(2rpx);
}

.back-login {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
  font-size: 28rpx;
}

.back-text {
  color: #9ca3af;
}

.back-btn-text {
  color: #165dff;
  text-decoration: underline;
}

.agreement {
  display: flex;
  justify-content: center;
  margin-top: 30rpx;
  font-size: 24rpx;
}

.agreement .text {
  padding: 0 4rpx;
  color: #9ca3af;
}

.agreement .link {
  color: #165dff;
}
</style>
